package com.gmail.blackdog1987.onedollar.service.impl;

import com.gmail.blackdog1987.onedollar.dao.*;
import com.gmail.blackdog1987.onedollar.entity.*;
import com.gmail.blackdog1987.onedollar.entity.base.Page;
import com.gmail.blackdog1987.onedollar.service.LuckyBagService;
import com.gmail.blackdog1987.onedollar.util.ErrorCode;
import com.gmail.blackdog1987.onedollar.util.JsonChangeUtil;
import com.gmail.blackdog1987.onedollar.util.LuckyBagUtil;
import com.gmail.blackdog1987.onedollar.vo.LuckyBagVO;
import com.gmail.blackdog1987.onedollar.web.controller.AlipayController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.*;

@Service("luckyBagServiceImpl")
public class LuckyBagServiceImpl implements LuckyBagService {
	@Autowired
	private LuckyBagDao luckyBagDao;
	@Autowired
	private LuckyBagConsumeDao luckyBagConsumeDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private LuckyBagConsumeHistoryDao luckyBagConsumeHistoryDao;
	@Autowired
	private AlipayCallbackDao alipayCallbackDao;
	@Autowired
	private UserLuckyBagDao userLuckyBagDao;
	@Autowired
	private UserChargeDao userChargeDao;
	@Override
	public Map<String, Object> doSend(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String userid = filter.get("userid");
		String serialnumber = filter.get("serialnumber");
		String total = filter.get("total");
		String count = filter.get("count");
		String type = filter.get("type");
		String wish = filter.get("wish");
		String phone = filter.get("phone");
		String pwd = filter.get("pwd");
		double totalValue = Double.valueOf(total);
		int countValue = Integer.valueOf(count);
		int typeValue = Integer.valueOf(type);
		// 检查发送人的余额是否足够，足够才发
		TUserEntity userEntity = userDao.get(Integer.valueOf(userid));
		if(userEntity==null||0==userEntity.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}
		if(!userEntity.getUserPwd().equals(pwd)){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "密码不正确").getResultMap();
		}
		if(totalValue==0){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "你一分钱都不塞进红包啊？").getResultMap();
		}
		if(userEntity.getMoney()==null||userEntity.getMoney().doubleValue() < totalValue){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTENOUGHMONEY, "您的余额不足哟").getResultMap();
		}
		userEntity.setMoney(userEntity.getMoney().subtract(new BigDecimal(totalValue)));
		int useridValue = Integer.valueOf(userid);
		// valid inpu
		// 创建红包
		TLuckybagEntity obj = new TLuckybagEntity();
		obj.setSender(useridValue);
		obj.setAvailable(totalValue);
		obj.setAvailablecount(countValue);
		obj.setTotal(totalValue);
		obj.setTotalcount(countValue);
		obj.setSendtime(new Timestamp(System.currentTimeMillis()));
		obj.setContent(wish);
		obj.setType(typeValue);
		obj.setSerialnumber(serialnumber);

		TUserChargeEntity chargeEntity = new TUserChargeEntity();
		chargeEntity.setChannel(TUserChargeEntity.SENDLUCKYMONEY);
		chargeEntity.setValue(new BigDecimal(totalValue));
		chargeEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
		chargeEntity.setUserId(useridValue);
		userChargeDao.create(chargeEntity);

		if(totalValue*100<countValue){
			resultJson = JsonChangeUtil.setResultJson(ErrorCode.LUCKYBAG_INVALIDINPUT, "请输入正确的金额");
			return resultJson.getResultMap();
		}
		Integer objId = (Integer) luckyBagDao.create(obj);
		obj.setId(objId);
		if(typeValue==0){
			// 创建子红包，等人抢
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("year", Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
			param.put("userid", Integer.valueOf(userid));

			TUserLuckybagEntity userLuckybagEntity;
			List<TUserLuckybagEntity> userLuckybagEntities = userLuckyBagDao.find(param);
			if(userLuckybagEntities==null||userLuckybagEntities.size()==0){
				userLuckybagEntity = new TUserLuckybagEntity();
				userLuckybagEntity.setUserid(Integer.valueOf(userid));
				userLuckybagEntity.setYear(Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
			}else{
				userLuckybagEntity = userLuckybagEntities.get(0);
			}

			userLuckybagEntity.setSend(userLuckybagEntity.getSend() == null ? totalValue : userLuckybagEntity.getSend() + totalValue);
			userLuckybagEntity.setSendcount(userLuckybagEntity.getSendcount()==null?countValue:userLuckybagEntity.getSendcount()+countValue);

			userLuckyBagDao.save(userLuckybagEntity);
			double[] consumes = LuckyBagUtil.generateLuckyBagConsume(totalValue, countValue);
			List<TLuckybagConsumeEntity> list = new ArrayList<TLuckybagConsumeEntity>();
			int winnner = 0;
			double winnerValue = 0;
			for(int i = 0; i < countValue; i ++){
				if(countValue > winnerValue){
					winnerValue = countValue;
					winnner = i;
				}
				TLuckybagConsumeEntity e = new TLuckybagConsumeEntity();
				e.setLuckybagId(obj.getId());
				e.setMoney(consumes[i]);
				e.setStatus(0);
				e.setOrderby(i);
				e.setWin(0);
				list.add(e);
			}
			list.get(winnner).setWin(1);
//			luckyBagConsumeDao.create(list.get(0));
			luckyBagConsumeDao.saveAll(list);
			userDao.update(userEntity);
		} else if (typeValue==2){
			// 检查被发送的人注册了没有，没有注册就帮他注册一个，并且挂上红包，然后发短信邀请他
			TUserEntity user = userDao.getUniqueBy("userAccount", phone);
			if(user == null){ 	// 没有注册，帮忙注册，并且邀请
				user = new TUserEntity();
				user.setAddTime(new Timestamp(System.currentTimeMillis()));
				user.setUserAccount(phone);
				user.setUserPwd(String.valueOf(new Random().nextFloat()));
				user.setStatus(-1);
				user.setUpdateTime(user.getAddTime());
				Integer uid = (Integer)userDao.create(user);
				// 发送短信提醒他
				user.setUserId(uid);
			}
			// 创建子红包，等人抢
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("year", Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
			param.put("userid", Integer.valueOf(userid));
			TUserLuckybagEntity userLuckybagEntity = new TUserLuckybagEntity();
			List<TUserLuckybagEntity> userLuckybagEntities = userLuckyBagDao.find(param);
			if(userLuckybagEntities==null||userLuckybagEntities.size()==0){
				userLuckybagEntity = new TUserLuckybagEntity();
				userLuckybagEntity.setUserid(Integer.valueOf(userid));
				userLuckybagEntity.setYear(Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
			}else{
				userLuckybagEntity = userLuckybagEntities.get(0);
			}

			userLuckybagEntity.setSend(userLuckybagEntity.getSend()==null?totalValue:userLuckybagEntity.getSend() + totalValue);
			userLuckybagEntity.setSendcount(userLuckybagEntity.getSendcount()==null?1:userLuckybagEntity.getSendcount()+1);

			userLuckyBagDao.save(userLuckybagEntity);

			TLuckybagConsumeEntity e = new TLuckybagConsumeEntity();
			e.setOrderby(1);
			e.setWin(1);
			e.setMoney(totalValue);
			e.setConsumer(user.getUserId());
			e.setStatus(0);
			e.setLuckybagId(obj.getId());
			luckyBagConsumeDao.create(e);
			userDao.update(userEntity);
		}else if (typeValue==1){
			double singleCount = totalValue/countValue;
			singleCount = new BigDecimal(singleCount).setScale(2, RoundingMode.DOWN).doubleValue();
			List<TLuckybagConsumeEntity> list = new ArrayList<TLuckybagConsumeEntity>();
			for(int i = 0; i < countValue; i ++){
				TLuckybagConsumeEntity e = new TLuckybagConsumeEntity();
				e.setLuckybagId(obj.getId());
				e.setMoney(singleCount);
				e.setOrderby(i);
				e.setStatus(0);
				e.setWin(1);
				list.add(e);
			}
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("year", Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
			param.put("userid", Integer.valueOf(userid));
			TUserLuckybagEntity userLuckybagEntity = new TUserLuckybagEntity();
			List<TUserLuckybagEntity> userLuckybagEntities = userLuckyBagDao.find(param);
			if(userLuckybagEntities==null||userLuckybagEntities.size()==0){
				userLuckybagEntity = new TUserLuckybagEntity();
				userLuckybagEntity.setUserid(Integer.valueOf(userid));
				userLuckybagEntity.setYear(Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
			}else{
				userLuckybagEntity = userLuckybagEntities.get(0);
			}

			userLuckybagEntity.setSend(userLuckybagEntity.getSend()==null?totalValue:userLuckybagEntity.getSend() + totalValue);
			userLuckybagEntity.setSendcount(userLuckybagEntity.getSendcount()==null?countValue:userLuckybagEntity.getSendcount()+countValue);

			userLuckyBagDao.save(userLuckybagEntity);
			luckyBagConsumeDao.saveAll(list);
			userDao.update(userEntity);
		}else {
			JsonChangeUtil.setResultJson(ErrorCode.LUCKYBAG_INVALIDINPUT, "请输入正确的金额");
			return resultJson.getResultMap();
		}
		return resultJson.getResultMap();
	}

	@Override
	public boolean doAlipaySend(Map<String, String> filter) {
		TAlipayCallbackEntity callbackEntity = AlipayController.generateCallbackEntity(filter);

		String orderid = callbackEntity.getOutTradeNo();
		BigDecimal totalFee = callbackEntity.getTotalFee();
		String notifyId = callbackEntity.getNotifyId();
		callbackEntity.setSubject("红包");

		if(alipayCallbackDao.check(notifyId) > 0){
			return false;
		}



		TUserEntity user = userDao.get(Integer.valueOf(orderid));
		user.setMoney(user.getMoney().add(totalFee));
		userDao.update(user);
		alipayCallbackDao.create(callbackEntity);
		return true;
	}

	@Override
	public Map<String, Object> doConsume(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String userid = filter.get("userid");
		String luckybagid = filter.get("luckybagid");

		TLuckybagEntity bag = luckyBagDao.get(Integer.valueOf(luckybagid));
		if(bag.getAvailablecount()==0){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTENOUGHMONEY, "红包已经被抢完啦！").getResultMap();
		}

		TUserEntity userEntity = userDao.get(Integer.valueOf(userid));
		if(userEntity==null||0==userEntity.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}

		TLuckybagConsumeEntity entity = luckyBagConsumeDao.consume(userid, luckybagid);
		if(entity!=null){ // 抢成功
			entity.setConsumetime(new Timestamp(System.currentTimeMillis()));
			entity.setConsumer(Integer.valueOf(userid));
			entity.setStatus(1);
			luckyBagConsumeDao.update(entity);

			bag.setAvailablecount(bag.getAvailablecount()-1);
			if(bag.getAvailablecount()==0){
				bag.setAvailable(0.0);
			}else{
				bag.setAvailable(new BigDecimal(bag.getAvailable()).subtract(new BigDecimal(entity.getMoney())).doubleValue());
			}
			luckyBagDao.update(bag);

			TLuckybagConsumeHistoryEntity historyEntity = new TLuckybagConsumeHistoryEntity();
			historyEntity.setConsumeId(entity.getId());
			historyEntity.setUserId(Integer.valueOf(userid));
			historyEntity.setLuckybagId(entity.getLuckybagId());
			luckyBagConsumeHistoryDao.create(historyEntity);

			if(userEntity.getMoney()==null){
				userEntity.setMoney(new BigDecimal(0));
			}
			userEntity.setMoney(userEntity.getMoney().add(new BigDecimal(entity.getMoney())));
			userEntity.setIncomeTotal(userEntity.getIncomeTotal()==null?new BigDecimal(entity.getMoney()):userEntity.getIncomeTotal().add(new BigDecimal(entity.getMoney())));
			userEntity.setIncomeNow(userEntity.getIncomeNow()==null?new BigDecimal(entity.getMoney()):userEntity.getIncomeNow().add(new BigDecimal(entity.getMoney())));
			userDao.update(userEntity);

			Map<String, Object> param = new HashMap<String, Object>();
			param.put("year", Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
			param.put("userid", Integer.valueOf(userid));
			TUserLuckybagEntity userLuckybagEntity = new TUserLuckybagEntity();
			List<TUserLuckybagEntity> userLuckybagEntities = userLuckyBagDao.find(param);
			if(userLuckybagEntities==null||userLuckybagEntities.size()==0){
				userLuckybagEntity = new TUserLuckybagEntity();
				userLuckybagEntity.setUserid(Integer.valueOf(userid));
				userLuckybagEntity.setYear(Integer.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
				userLuckybagEntity.setConsumecount(0);
				userLuckybagEntity.setConsume(0.0);
				userLuckybagEntity.setSend(0.0);
				userLuckybagEntity.setSendcount(0);
			}else{
				userLuckybagEntity = userLuckybagEntities.get(0);
			}

			userLuckybagEntity.setConsume(userLuckybagEntity.getConsume()==null?entity.getMoney():(userLuckybagEntity.getConsume() + entity.getMoney()));
			userLuckybagEntity.setConsumecount(userLuckybagEntity.getConsumecount() == null ? 1 : userLuckybagEntity.getConsumecount() + 1);

			userLuckyBagDao.save(userLuckybagEntity);

			LuckyBagVO vo = new LuckyBagVO();
			vo.setConsumer(Integer.valueOf(userid));
			vo.setConsumetime(entity.getConsumetime());
			vo.setContent(bag.getContent());
			vo.setId(Integer.valueOf(luckybagid));
			vo.setLuckybagId(bag.getId());
			vo.setMoney(entity.getMoney());
			vo.setOrderby(entity.getOrderby());
			vo.setWin(entity.getWin());

			TUserEntity u = userDao.get(Integer.valueOf(bag.getSender()));
			vo.setNickName(userEntity.getNickName());
			vo.setHead(u.getHead());
			vo.setSenderName(u.getNickName());
			vo.setSendtime(bag.getSendtime());

			TUserChargeEntity chargeEntity = new TUserChargeEntity();
			chargeEntity.setChannel(TUserChargeEntity.GETLUCKYMONEY);
			chargeEntity.setValue(new BigDecimal(entity.getMoney()));
			chargeEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
			chargeEntity.setUserId(Integer.valueOf(userid));
			userChargeDao.create(chargeEntity);

			return JsonChangeUtil.setResultJson(vo).getResultMap();
		}else{
			// 抢不成功
			resultJson = JsonChangeUtil.setResultJson(ErrorCode.LUCKYBAG_LATE, "红包已经被人抢走啦");
		}
		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> getList(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String userid = filter.get("userid");
		String pageIndex = filter.get("pageindex");
		String pageSize = filter.get("pagesize");
		String history = filter.get("history");
		String type = filter.get("type");

		int index = 1;
		int size = 10;
		if(pageIndex!=null&&pageIndex.length()!=0){
			index = Integer.valueOf(pageIndex);
			if(index<1){
				index = 1;
			}
		}
		if(pageSize!=null&&pageSize.length()!=0){
			size = Integer.valueOf(pageSize);
			if(size==0){
				size = 10;
			}
		}
		if(history==null||history.length()==0){
			history = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
		}
		Page page;
		if(type==null||type.length()==0){
			page = luckyBagConsumeDao.queryConsumeForPage(userid, index, size, Integer.valueOf(history));
		}else{
			int i = Integer.valueOf(type);
			if(i==0){
				page = luckyBagConsumeDao.queryConsumeForPage(userid, index, size, Integer.valueOf(history));
			}else{
				page = luckyBagConsumeDao.querySendForPage(userid, index, size, Integer.valueOf(history));
			}
		}

		resultJson.put("data", page);

		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> getNewList(Map<String, String> filter) {
		String userid = filter.get("userid");

		return JsonChangeUtil.setResultJSONList(luckyBagConsumeDao.queryNew(userid)).getResultMap();
	}

	@Override
	public Map<String, Object> getNewCount(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String userid = filter.get("userid");

		int count = luckyBagConsumeDao.queryNewCount(userid);
		resultJson.put("data", count);

		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> getNew(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String userid = filter.get("userid");

		resultJson.put("data", luckyBagConsumeDao.queryNewest(userid));

		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> getLuckyBagYear(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");
		String userid = filter.get("userid");
		String year = filter.get("year");

		Map<String,Object> param = new HashMap<String, Object>();
		param.put("userid", Integer.valueOf(userid));
		param.put("year", Integer.valueOf(year));
		List<TUserLuckybagEntity> bags = userLuckyBagDao.find(param);
		if(bags==null||bags.size()==0){
			return resultJson.getResultMap();
		}
		return JsonChangeUtil.setResultJson(bags.get(0)).getResultMap();
	}

	@Override
	public void doGetBackNotReceive() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DATE, -3);
//		c.add(Calendar.MINUTE, -10);
		List<TLuckybagEntity> entities = luckyBagDao.queryNotReceiveBeforeTime(c.getTime());
		List<TUserEntity> users = luckyBagDao.querySenderNotReceiveBeforeTime(c.getTime());
		Map<Integer, TUserChargeEntity> chargeMap = new HashMap<Integer, TUserChargeEntity>();
		for (TLuckybagEntity e: entities){		// 遍历所有红包
			for (TUserEntity u: users){
				if(u.getUserId() == e.getSender()){
					u.setMoney(u.getMoney().add(new BigDecimal(e.getAvailable())));		// 回收余额
					TUserChargeEntity chargeEntity;
					if(chargeMap.containsKey(u.getUserId())){
						chargeEntity = chargeMap.get(u.getUserId());
						chargeEntity.setValue(chargeEntity.getValue() == null ? new BigDecimal(e.getAvailable()) : chargeEntity.getValue().add(new BigDecimal(e.getAvailable())));
					}else{
						chargeEntity = new TUserChargeEntity();
						chargeEntity.setUserId(u.getUserId());
						chargeEntity.setValue(new BigDecimal(e.getAvailable()));
						chargeEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
						chargeEntity.setType(0);
						chargeEntity.setChannel(TUserChargeEntity.GETBACKLUCKYMONEY);	// 红包退回
						chargeMap.put(u.getUserId(), chargeEntity);
					}
				}
			}
			e.setAvailable(0.0);
			e.setAvailablecount(0);
		}
		if(entities!=null&&entities.size()!=0){
			luckyBagConsumeDao.disableNotReceiveBeforeTime(c.getTime());
		}
		userChargeDao.saveAll(chargeMap.values());		// 日志
		luckyBagDao.saveAll(entities);		// 红包设置
		userDao.saveAll(users);		// 余额
//		System.err.print("回收红包完成...");
	}
}
